package org.m2acsi.control;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.ManagedBean;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import org.m2acsi.entities.Task;
import org.m2acsi.entities.User;

@Named
@RequestScoped
@ManagedBean
public class AdminTaskBean extends BaseBean implements Serializable {

    private Task task = new Task();
    private String tmpDate;
    private String tmpTime;
    private Map<User, Boolean> checked;
    private Map<Long, String> checkedS;
    private long tmpTaskId;

    public AdminTaskBean() {
        super();
        checked = new HashMap<>();
        checkedS = new HashMap<>();
    }

    public Map<Long, String> getCheckedS() {
        return checkedS;
    }

    public void setCheckedS(Map<Long, String> checkedS) {
        this.checkedS = checkedS;
    }

    public Task getTask() {
        return task;
    }

    public void setTask(Task task) {
        this.task = task;
    }

    public String getTmpDate() {
        return tmpDate;
    }

    public void setTmpDate(String tmpDate) {
        this.tmpDate = tmpDate;
    }

    public String getTmpTime() {
        return tmpTime;
    }

    public void setTmpTime(String tmpTime) {
        this.tmpTime = tmpTime;
    }

    public Map<User, Boolean> getChecked() {
        return checked;
    }

    public void setChecked(Map<User, Boolean> checked) {
        this.checked = checked;
    }

    public long getTmpTaskId() {
        return tmpTaskId;
    }

    public void setTmpTaskId(long tmpTaskId) {
        this.tmpTaskId = tmpTaskId;
    }

    public List<User> getUsers() {
        List< User> lUser = userEjb.findAll();
        String authorEmail = getAuthenticatedUser().getEmail();
        User toDelete = null;
        for (User u : lUser) {
            if (u.getEmail().equals(authorEmail)) {
                toDelete = u;
            }
        }
        lUser.remove(toDelete);
        return lUser;
    }

    public void addTask() {
        //Recupérer l'author
        task.setAuthor(getAuthenticatedUser());
        //Conversion tmpDate to Date
        String allDate = tmpDate + " " + tmpTime;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        sdf.setLenient(false);
        Date deadline = null;
        try {
            deadline = sdf.parse(allDate);
            if (deadline.compareTo(new Date()) <= 0) {
                FacesContext.getCurrentInstance().addMessage("task-add-form:deadlineDate", new FacesMessage("The date must be later than the current date"));
            } else {
                task.setDeadline(deadline);
                List<Task> lAuthor = getAuthenticatedUser().getAuthor();
                lAuthor.add(task);
                getAuthenticatedUser().setAuthor(lAuthor);
                taskEjb.save(task);
                //Add contributors
                List<User> contributorsList = new ArrayList<>();
                for (User u : checked.keySet()) {
                    if (checked.get(u)) {
                        u.getContributions().add(task);
                        //userEjb.update(u);
                        contributorsList.add(u);
                    }
                }
                task.setContributors(contributorsList);
                taskEjb.update(task);
                userEjb.update(getAuthenticatedUser());
                redirectWithMessage("/faces/admin/taskList.xhtml", "Your task has been created.");
            }
        } catch (ParseException ex) {
            FacesContext.getCurrentInstance().addMessage("deadlineDate", new FacesMessage("The deadline is required"));
        }
    }

    public void loadTask() {
        task = taskEjb.find(tmpTaskId);
        if (task == null) {
            hackRedirect("try to change an id.");
        } else {
            tmpDate = (new SimpleDateFormat("yyyy-MM-dd")).format(task.getDeadline());
            tmpTime = (new SimpleDateFormat("HH:mm")).format(task.getDeadline());
            System.out.println(getUsers().size());
            for (User u : this.getUsers()) {
                boolean add = false;
                for (User user : task.getContributors()) {
                    if (u.getId() == user.getId()) {
                        add = true;
                    }
                }
                if (add) {
                    checked.put(u, Boolean.TRUE);
                    checkedS.put(u.getId(), "checked");
                } else {
                    checked.put(u, Boolean.FALSE);
                    checkedS.put(u.getId(), "");
                }
            }
        }
        for (Map.Entry<User, Boolean> entry : checked.entrySet()) {
            User user = entry.getKey();
            Boolean boolean1 = entry.getValue();
            System.out.println(user.getFirstname() + "\t" + boolean1);
        }
    }

    public void editTask() {
        Task taskBD = taskEjb.find(tmpTaskId);
        taskBD.setTitle(task.getTitle());
        //Conversion tmpDate to Date
        String allDate = tmpDate + " " + tmpTime;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        sdf.setLenient(false);
        Date deadline = null;
        try {
            deadline = sdf.parse(allDate);
            if (deadline.compareTo(new Date()) <= 0) {
                FacesContext.getCurrentInstance().addMessage("task-add-form:deadlineDate", new FacesMessage("The date must be later than the current date"));
            } else {
                taskBD.setDeadline(deadline);
            }
        } catch (ParseException ex) {
            FacesContext.getCurrentInstance().addMessage("deadlineDate", new FacesMessage("The deadline is required"));
        }
        taskBD.setDescription(task.getDescription());
        taskEjb.update(taskBD);
        //Contributors
        List<User> contributorsList = new ArrayList<>();
        boolean alreadyContributors = false;
        for (User u : checked.keySet()) {
            if (checked.get(u)) {
                for (User contri : taskBD.getContributors()) {
                    if (u.getId() == contri.getId()) {
                        alreadyContributors = true;
                    }
                }
                if (!alreadyContributors) {
                    u.getContributions().add(taskBD);
                }
                contributorsList.add(u);
                alreadyContributors = false;
            } else {
                for (User contri : taskBD.getContributors()) {
                    if (u.getId() == contri.getId()) {
                        u.getContributions().remove(taskBD);
                    }
                }
            }
        }
        task.setContributors(contributorsList);
        taskEjb.update(task);
    }
}
